/**
 * Created by shopnc on 2016/1/26.
 */
//定义表格
var dtGridColumns = [{
    id: 'name',
    title: '公众号名称',
    type: 'string',
    headerClass: 'text-left width-200',
    columnClass: 'text-left width-200',
    fastSort: false,
    fastQuery: true,
    fastQueryType: 'eq'
}, {
    id: 'account',
    title: '微信号',
    type: 'string',
    headerClass: 'text-left',
    columnClass: 'text-left',
    fastSort: false,
    fastQuery: true,
    fastQueryType: 'eq',
	hideType: 'xs|sm|md'
}, {
    id: 'appid',
    title: 'APPID',
    type: 'string',
    headerClass: 'text-left width-200',
    columnClass: 'text-left width-200',
    fastSort: false,
    fastQuery: true,
    fastQueryType: 'eq',
	hideType: 'xs|sm'
}, {
    id: 'appsecret',
    title: 'APPSECRET',
    type: 'string',
    headerClass: 'text-left width-200',
    columnClass: 'text-left width-200',
    fastSort: false,
    fastQuery: true,
    fastQueryType: 'eq',
	hideType: 'xs|sm'
}, {
    id: 'operation',
    title: '管理操作',
    type: 'string',
    columnClass: 'text-center width-300',
    fastSort: false,
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        content +=
            '<a data-toggle="modal" href="#editModal" class="btn btn-primary btn-sm m-r-10" data-no="' + dataNo + '" ><i class="fa fa-edit"></i>&nbsp;编辑&nbsp;</a>' + '</div>';

        content +=
            '<div class="btn-group">' +
            '<a data-toggle="dropdown" href="javascript:;" aria-expanded="false" class="btn btn-info btn-sm dropdown-toggle m-r-10"> <i class="fa fa-gears"></i>' +
            '&nbsp;自定义菜单&nbsp;' +
            '<span class="caret"></span>' +
            '</a>' +
            '<ul class="dropdown-menu dropdown-menu-left">' +
            '<li><a data-toggle="modal" href="#menuModal" data-wxname="' + record.name + '" data-no="' + record.id + '" data-num="1" ><i class="fa fa-list-ol m-r-5" aria-hidden="true"></i>菜单按钮A</a></li>' +
            '<li><a data-toggle="modal"  href="#menuModal" data-wxname="' + record.name + '" data-no="' + record.id + '" data-num="2" ><i class="fa fa-list-ol m-r-5" aria-hidden="true"></i>菜单按钮B</a></li>' +
            '<li><a data-toggle="modal"  href="#menuModal" data-wxname="' + record.name + '" data-no="' + record.id + '" data-num="3" ><i class="fa fa-list-ol m-r-5" aria-hidden="true"></i>菜单按钮C</a></li>' +
            '</ul>' +
            '</div>';

        content += "<a href='javascript:;' class='btn btn-sm btn-danger' onclick='reason.del(" + record.id + ")'><i class='fa fa-trash-o'></i>删除</a>";

        return content;
    }
}];
var dtGridOption = {
    lang: 'zh-cn',
    ajaxLoad: true,
    loadURL: ncGlobal.adminRoot + 'wxaccount/json/list',
    exportFileName: '微信公众号列表',
    columns: dtGridColumns,
    gridContainer: 'dtGridContainer',
    toolbarContainer: 'dtGridToolBarContainer',
    tools: '',
    pageSize: 10,
    pageSizeLimit: [10, 20, 50],
    onGridComplete: function (grid) {

    }
};
var grid = $.fn.DtGrid.init(dtGridOption);
grid.sortParameter.sortType = 1;


var reason = function () {
    var currBtnInfo, currBtnClickReplyList, currWxId, currBtnNum, $currBtnLi,
        tplModalLi = '<li><a href="javascript:;" class="text" title="<%=name%>"><span data-nc-text><%=name%></span></a><a href="javascript:;" data-nc-delete class="del" title="删除"><i class="fa fa-trash-o"></i></a></li>'
        ;
    var DATA_KEY = 'nc.data',
        MAX_BTN = 5,
        CN_BTN_SELECTED = 'selected',
        CN_ADDBTN_WHITE = 'btn-white',
        CN_ADDBTN_DEFAULT = 'btn-default'
        ;
    /**
     * 修改当前选择的数据
     * @param data
     * @private
     */
    function _setCurrentData(data) {
        try {
            currBtnInfo = data.data.btninfo;
            currBtnClickReplyList = data.data.clickReplyList;
        } catch (e) {
            currBtnInfo = null;
            currBtnClickReplyList = null;
        }
    }

    /**
     * 渲染modal 对话框
     */
    function _renderModal(data) {
        $("#btnMenuListPanel").empty();
        $.isArray(data) && data.forEach(function (currValue) {
            var _h = $(ncTemplate(tplModalLi)(currValue));
            _h.data(DATA_KEY, currValue);
            $("#btnMenuListPanel").append(_h);
        });
        //刷新新增按钮
        _refreshAddBtn();
        //重置对话框上的input
        _renderInputForEleData();
        //清楚抢钱选择的li
        $currBtnLi = null;
    }

    /**
     * 绑定对话框上的事件
     * @private
     */
    function _bindEventsForModal() {
        //btn menu li click
        $("#btnMenuListPanel").off("click", "li").on("click", 'li', function () {
            console.log("li click ");
            var $this = $(this), _eleData = $this.data(DATA_KEY);
            $currBtnLi = $this;
            $this.siblings("li").removeClass(CN_BTN_SELECTED).end().addClass(CN_BTN_SELECTED);
            //将元素上的数据显示到input 上面去
            _renderInputForEleData(_eleData)
        });
        //操作类型选择
        $("#editSubBtnType").off("change").on("change", function () {
            var $this = $(this), value = $this.val();
            console.log("btn tyep change , value is : ", value);
            if (value == "click") {
                $("#editSubBtnUrlPanel").hide();
                $("#editSubBtnClickReplyPanel").show();
                $("#editSubBtnUrl").removeAttr("data-parsley-required").removeAttr("data-parsley-type");
                $("#subBtnClickReply").attr("data-parsley-required" ,"true");
            } else {
                $("#editSubBtnUrlPanel").show();
                $("#editSubBtnClickReplyPanel").hide();
                $("#editSubBtnUrl").attr( {"data-parsley-required" : "true" , "data-parsley-type" : "url"} );
                $("#subBtnClickReply").removeAttr("data-parsley-required");
            }
        });
        //新建
        $("#editSubBtnAdd").off('click').on('click', function () {
            var $this = $(this);
            if ($this.hasClass(CN_ADDBTN_DEFAULT)) {
                _alert("子菜单最多只能设置" + MAX_BTN + "个");
                return;
            }
            _newBtnMenu();
        });
        //删除
        $("#btnMenuListPanel").off('click', 'a[data-nc-delete]').on('click', 'a[data-nc-delete]', function (event) {
            console.log("删除");
            event.preventDefault();
            event.stopPropagation();
            var $par = $(this).closest("li") , id = $par.data(DATA_KEY).id;

            id && _delBtnMenu(id)
            $par.remove();
            _refreshAddBtn();
            $currBtnLi = null ;
        });
        //保存设置
        $("#editSubBtnSave").off("click").on('click', function () {
            console.log('保存设置');
            if (!$currBtnLi){
                _alert("请选择一个标签");
                return ;
            }
            $("#editSubBtnForm").psly().validate() && _updateCurrentEleDataFormInput();
        });
        //同步设置
        $("#editSubBtnUpdate").off("click").on('click', function () {
            console.log('更新设置');
            _updateData();
        });

        //排序
        $("#btnMenuListPanel").sortable({
            items: "li",
            helper: "clone"
        });
    }

    /**
     * 删除子菜单
     * @private
     */
    function _delBtnMenu (id , cb){
        $.post(ncGlobal.adminRoot + 'wxsubmenu/json/del' , {
            id:id
        } , function(xhr ){
            if(xhr.code == 200 ){
               _alert("删除成功");
            }
        });
    }

    /**
     * 刷新验证
     * @private
     */
    function _resetSubButtonForm(){

    }

    /**
     * 新增子菜单
     * @private
     */
    function _newBtnMenu() {
        var _defalutData = {
                topBtn: currBtnInfo.id,
                wxId:currBtnInfo.wxId ,
                name:'新菜单'
            },
            _h = $(ncTemplate(tplModalLi)(_defalutData));
        _h.data(DATA_KEY, _defalutData);
        $("#btnMenuListPanel").append(_h);
        _h.trigger("click");
        //刷新新曾按钮
        _refreshAddBtn();
    }

    /**
     *  将元素上的数据显示到input
     * @private
     */
    function _renderInputForEleData(data) {
        console.log("将元素上的数据显示到input");
        if (data) {
            $("#editSubBtnType").val(data.type ? data.type : 'view').trigger("change");
            if (data.type == 'view'){
                $("#editSubBtnUrl").val(data.data ? data.data : '');
                $("#subBtnClickReply").selectpicker("val" , '')
            }else{
                $("#editSubBtnUrl").val('');
                $("#subBtnClickReply").selectpicker("val" , data.data ? data.data : '')
            }
            $("#editSubBtnName").val(data.name ? data.name : "");
            $("#editSubBtnForm").psly().reset();
        } else {
            $("#editSubBtnUrl").val('');
            $("#editSubBtnName").val('');
            $("#editSubBtnType").val('view').trigger("change");
            $("#subBtnClickReply").selectpicker("val" , '');
            $("#editSubBtnForm").psly().reset();
        }
    }

    /**
     * 从当前的input 上更新数据到 $currBtnLi
     * @private
     */
    function _updateCurrentEleDataFormInput() {
        var _currData = $currBtnLi.data(DATA_KEY);
        _currData.topBtn = currBtnInfo.id;
        _currData.wxId = currBtnInfo.wxId;
        _currData.name = $("#editSubBtnName").val();
        _currData.type = $("#editSubBtnType").val();
        _currData.data = $("#editSubBtnType").val() == 'view' ? $("#editSubBtnUrl").val() : $("#subBtnClickReply").val();

        //
        $currBtnLi.find('span[data-nc-text]').html(_currData.name);
        _alert("保存成功");
    }

    /**
     * 从modal上获取需要保存的数据
     * @private
     */
    function _getPostDataFormElement() {
        return $.map($("#btnMenuListPanel").find("li"), function (currValue , index ) {
            var _data = $(currValue).data(DATA_KEY);
            _data.sortNo = index ;
            return _data.type  ? _data  : null ;
        });
    }

    /**
     * 刷新新增按钮
     * @private
     */
    function _refreshAddBtn() {
        var $editSubBtnAdd = $("#editSubBtnAdd");
        if ($("#btnMenuListPanel li").length >= MAX_BTN) {
            $editSubBtnAdd.removeClass(CN_ADDBTN_WHITE).addClass(CN_ADDBTN_DEFAULT);
        } else {
            $editSubBtnAdd.removeClass(CN_ADDBTN_DEFAULT).addClass(CN_ADDBTN_WHITE);
        }
    }

    /**
     * 提交更新
     * @private
     */
    function _updateData() {
        var _d = _getPostDataFormElement();
        $.post(ncGlobal.adminRoot + "submenu/json/save", {
            btnList: _d ? JSON.stringify(_d) : ''
        }, function (xhr) {
            if (xhr.code == 200 ){
               $("#subButtonModal").modal("toggle");
               $.get(ncGlobal.adminRoot + "wxmenu/update/" + currBtnInfo.wxId, function (xhrUpdate) {
                   _alert(xhrUpdate.message);

                   xhrUpdate.code == 200 &&  grid.reload(true)
               }); 
            }else{
                _alert(xhr.message);
            }
        });
        
    }

    /**
     * 绑定事件
     * @private
     */
    function _bindEvent() {
        //模糊查询
        $("#customSearch").click(function () {
            grid.fastQueryParameters = new Object();
            grid.fastQueryParameters['eq_delFlag'] = 1;
            grid.fastQueryParameters['lk_account_or_lk_name'] = $('#keyword').val();
            grid.pager.startRecord = 0;
            grid.pager.nowPage = 1;
            grid.pager.recordCount = -1;
            grid.pager.pageCount = -1;
            grid.refresh(true);
        });
        //添加微信公众号时显示时
        $('#addModal').on('show.bs.modal', function (event) {
            $("#addForm").psly().reset();
            $(".alert-danger").remove()
        });
        //编辑微信公众号时显示时
        $('#editModal').on('show.bs.modal', function (event) {
            var
                button = $(event.relatedTarget),
                datano = button.data('no'),
                gridData = grid.sortOriginalDatas[datano],
                editForm = $("#editForm");
            $("#editWxId").val(gridData.id);
            $("#editWxName").val(gridData.name);
            $("#editWxOriName").val(gridData.oriName);
            $("#editWxAccount").val(gridData.account);
            $("#editWxAppid").val(gridData.appid);
            $("#editWxSecret").val(gridData.appsecret);
            $("#editWxToken").val(gridData.token);
            editForm.psly().reset();
            $(".alert-danger").remove()
        })
        //添加的form 成功返回时
        $("#addForm").on("nc.formSubmit.success", function () {
            $("#addReasonInfo").val('');
            $("#addReasonSort").val('');
            $("#addForm").psly().reset();
            $(".alert-danger").remove()
        })

        //弹出自定义菜单一级按钮设置
        $('#menuModal').on('show.bs.modal', function (event) {
            var name = $(event.relatedTarget).data('wxname');
            $("#tipWxName").text(name);
            var wxId = currWxId = $(event.relatedTarget).data('no');
            var btnNum = currBtnNum = $(event.relatedTarget).data('num');
            console.log('弹出自定义菜单一级按钮设置 btnNum is ', btnNum);

            $("#buttonNum").text(btnNum);
            $.getJSON(ncGlobal.adminRoot + "wxmenu/json/list/" + wxId + "/" + btnNum, function (data) {

                var btninfo ;
                //修改当前选择的数据
                _setCurrentData(data);
                if (data.code == 400) {
                    $('#menuModal').modal('hide');
                    // 模态框报错
                   _alert(data.message)
                    return;
                }

                $("#editBtnWxId").val(wxId);
                //按钮信息
                btninfo = data.data.btninfo;
                $("#editBtnId").val(btninfo.id);
                $("#editBtnName").val(btninfo.name);
                $("#editBtnType").val(btninfo.type ? btninfo.type : 'subbtn' ).trigger("change");
                $("#editBtnUrl").val(btninfo.type == 'view' ? btninfo.data : '' ) ;
                //点击事件列表
                var clickReplyList = data.data.clickReplyList;
                $("#BtnClickReply").empty().append('<option value="">请选择事件</option>');
                $("#subBtnClickReply").empty().append('<option value="">请选择事件</option>');
                for (var i = 0; i < clickReplyList.length; i++) {
                    var _h = "<option value='" + clickReplyList[i].code + "'>" + clickReplyList[i].title + "</option>" ;
                    $("#BtnClickReply").append(_h);
                    $("#subBtnClickReply").append(_h);
                }
                $("#subBtnClickReply").selectpicker({insertPosition:"before"});

                $("#BtnClickReply").selectpicker({insertPosition:"before"});
                $("#BtnClickReply").selectpicker("val" , btninfo.type == 'click' ? btninfo.data : '')
            });
            $("#menuForm").psly().reset();
        });

        //自定义按钮操作内容切换
        $('#editBtnType').change(function () {
            if ($('#editBtnType').val() == "view") {
                $("#btnHandleUrlPanel").show();
                $("#btnHandleClickPanel").hide();
                $("#btnHandleSubbtnPanel").hide();

                $("#editBtnUrl").attr({"data-parsley-required" :"true" ,"data-parsley-type":"url" } );
                $("#BtnClickReply").removeAttr("data-parsley-required");
            }
            if ($('#editBtnType').val() == "subbtn") {
                $("#btnHandleUrlPanel").hide();
                $("#btnHandleClickPanel").hide();
                $("#btnHandleSubbtnPanel").show();
                $("#editBtnUrl").removeAttr("data-parsley-required").removeAttr("data-parsley-type");
                $("#BtnClickReply").removeAttr("data-parsley-required");
            }
            if ($('#editBtnType').val() == "click") {
                $("#btnHandleUrlPanel").hide();
                $("#btnHandleClickPanel").show();
                $("#btnHandleSubbtnPanel").hide();
                $("#editBtnUrl").removeAttr("data-parsley-required").removeAttr("data-parsley-type");
                $("#BtnClickReply").attr("data-parsley-required","true");
            }
            $("#menuForm").psly().reset();
        });

        //弹出自定义菜单一级按钮设置
        $('#subButtonModal').on('show.bs.modal', function (event) {
            $.getJSON(ncGlobal.adminRoot + "submenu/json/list/" + currBtnInfo.id, function (data) {
                if (data.code == 400) {
                    $('#editModal').modal('hide');
                    // 模态框报错
                    $.ncAlert({
                        closeButtonText: "关闭",
                        autoCloseTime: 3,
                        content: data.message
                    })
                    return;
                }
                //渲染modal
                _renderModal(data.data);
            });
        });


        //对话框上绑定事件
        _bindEventsForModal();
    }

    ///
    function _alert(message) {
        $.ncAlert({
            content: message,
            autoCloseTime: 2
        });
    }

    //外部可调用
    return {
        init: function () {
            _bindEvent();
        },
        //删除
        del: function (id) {

            $.ncConfirm({
                url: ncGlobal.adminRoot + "wxaccount/json/del",
                data: {
                    id: id
                }
            });

        }
    }
}();


$(function () {
    grid.load();
    reason.init();
});